'use strict';

const Olt = require('./OLT');
const snmp = require('net-snmp');
const {
  createSession
} = require('../RZtelnet/CreateSession');
const common = require('../common');
class HWOLT extends Olt {
  constructor(options) {
    options.version = snmp.Version2c;
    super(options);
  }
  async getONUDetails(PONindex, ONUindex, me) {
    return new Promise(async (resolve, reject) => {
      const addr = this.options.ip + ':' + this.options.tPort;
      const F = PONindex.split('/')[0];
      const S = PONindex.split('/')[1];
      const P = PONindex.split('/')[2];
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        F,
        S,
        P,
        ONUindex,
      };
      me.proxyFlag = this.options.proxyFlag;
      try {
        const fn = function (msg) {
          if (msg.indexOf('The ONT ID has already existed') != -1) {
            return {
              result: false,
              message: 'The ONT ID has already existed'
            };
          } else if (msg.indexOf('SN already exists') != -1) {
            return {
              result: false,
              message: 'SN already exists'
            };
          } else if (msg.indexOf('The line profile does not exist') != -1) {
            return {
              result: false,
              message: 'The line profile does not exist',
            };
          } else if (msg.indexOf('The service profile does not exist') != -1) {
            return {
              result: false,
              message: 'The service profile does not exist',
            };
          } else if (msg.indexOf('The GEM index does not exist') != -1) {
            return {
              result: false,
              message: 'The GEM index does not exist'
            };
          } else if (msg.indexOf('VLAN does not exist') != -1) {
            return {
              result: false,
              message: 'VLAN does not exist'
            };
          } else if (msg.indexOf('The traffic table does not exist') != -1) {
            return {
              result: false,
              message: 'The traffic table does not exist',
            };
          } else if (msg.indexOf('Failure') != -1) {
            return {
              result: false,
              message: msg.substring(msg.indexOf('Failure:') + 8).trim(),
            };
          }
          return {
            result: true
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_ONU_DETAILS',
            oltHardVersion: 'NONE',
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        const dest = {
          'ONU interface': '',
          Name: '',
          Type: '',
          'Phase state': '',
          'Serial number': '',
          vlan: [],
          Tx: '',
          Rx: '',
        };
        if (resultArr.length !== 0) {
          console.log(resultArr)
          const onuStr = resultArr.find(str => str.indexOf('display ont info') !== -1);
          if (onuStr.indexOf('Failure') !== -1) {
            return null;
          }
          const onuArr = onuStr.split('\n');
          const onuInterface = onuArr.find(str => str.indexOf('F/S/P') !== -1);
          dest['ONU interface'] = onuInterface.split(':')[1].trim();
          const snStr = onuArr.find(str => str.match(/SN.*:/) !== null);
          const sn = snStr.split(':')[1].trim();
          dest['Serial number'] = sn.substring(sn.indexOf('(') + 1, sn.indexOf(')'));
          const onuTypeStr = onuArr.find(str => str.indexOf('Service profile name') !== -1);
          dest.Type = onuTypeStr.split(':')[1].trim();
          const onuStateStr = onuArr.find(str => str.indexOf('Run state') !== -1);
          dest['Phase state'] = onuStateStr.split(':')[1].trim();
          // 处理vlan
          const vlanStartRow = onuArr.findIndex(str => str.indexOf('Mapping VLAN') !== -1);
          let tArr = onuArr.slice(vlanStartRow);
          tArr = tArr.slice(tArr.findIndex(str => str.indexOf('--------') !== -1) + 1);
          const index = tArr.findIndex(str => str.indexOf('--------') !== -1);
          const vlanTitleStr = onuArr.find(str => str.indexOf('Mapping VLAN') !== -1);
          const vlanColPosition = vlanTitleStr.indexOf('VLAN');
          const vlanColEndPosition = vlanTitleStr.indexOf('Priority Port');
          const vlanRows = tArr.slice(0, index);
          if (vlanRows.length > 0) {
            vlanRows.forEach(str => {
              const vlan = str.substring(vlanColPosition, vlanColEndPosition).trim();
              dest.vlan.push(vlan);
            });
          }
          // 处理光功率
          const powerStr = resultArr.find(str => str.indexOf('display ont optical-info') !== -1);
          if (powerStr.indexOf('Failure') === -1) {
            const powerArr = powerStr.split('\n');
            const rx = powerArr.find(str => str.indexOf('Rx optical power') !== -1 && str.indexOf('CATV') === -1);
            const tx = powerArr.find(str => str.indexOf('Tx optical power') !== -1);
            dest.Tx = tx.split(':')[1] + '(dBm)';
            dest.Rx = rx.split(':')[1] + '(dBm)';
          }
          resolve(dest);
        } else {
          resolve(true);
        }
      } catch (error) {
        reject(error);
      }
    });
  }
  async GetCommunity_HW(me) {
    return new Promise(async (resolve, reject) => {
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const addr = this.options.ip + ':' + this.options.tPort;

      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
      };
      me.proxyFlag = this.options.proxyFlag;
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_COMMUNITY',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const msg = resultArr[0];
        const msg2 = resultArr[1];
        const reg = /Community name:(\s\w*\W*\s)/g;
        const arr = msg.match(reg);
        const arr2 = msg2.match(reg);
        const resultArray = [];
        arr.forEach(item => {
          resultArray.push(item.split(':')[1].trim());
        });
        arr2.forEach(item => {
          resultArray.push(item.split(':')[1].trim());
        });
        resolve(resultArray);
      } catch (error) {
        resolve(null);
      }
    });
  }
  async DeleteCommunity_HW(CommunityArr, me) {
    return new Promise(async (resolve, reject) => {
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const addr = this.options.ip + ':' + this.options.tPort;
      me.proxyFlag = this.options.proxyFlag;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
        CommunityArr,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'DELETE_COMMUNITY',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resolve(true);
      } catch (error) {
        reject(error);
      }
    });
  }
  async SetCommunity_HW(rocommunity, rwcommunity, me) {
    return new Promise(async (resolve, reject) => {
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const addr = this.options.ip + ':' + this.options.tPort;
      me.proxyFlag = this.options.proxyFlag;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
        rocommunity,
        rwcommunity,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'MODIFY_COMMUNITY',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resolve(true);
      } catch (error) {
        resolve(false);
      }
    });
  }
  async getCard_HW(oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '#' : systemName + '#',
      };
      me.proxyFlag = this.options.proxyFlag;
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'CARD_LIST',
            oltHardVersion,
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const msg = resultArr[0];
        const lines = msg
          .replace(/(-{2,})\sMore.*(\u001B\[37D)\s*\2/g, '')
          .split('\n');
        const titleArray = [
          'SlotID',
          'BoardName',
          'Status',
          'SubType0',
          'SubType1',
          'Online/Offline',
        ];
        const colInfo = [];
        const title = lines.filter(
          value => value.indexOf(titleArray[0]) != -1
        );
        titleArray.forEach(titleItem =>
          colInfo.push(title[0].indexOf(titleItem))
        );
        const contents = lines.filter(
          value =>
          value.indexOf('---') == -1 &&
          value.indexOf('display board') == -1 &&
          value.indexOf(titleArray[0]) == -1 &&
          value.indexOf('>') == -1
        );
        const arr = [];
        contents.forEach(item => {
          const obj = new Object();
          obj[titleArray[0]] = item.substring(colInfo[0], colInfo[1]);
          obj[titleArray[1]] = item.substring(colInfo[1], colInfo[2]);
          obj[titleArray[2]] = item.substring(colInfo[2], colInfo[3]);
          obj[titleArray[3]] = item.substring(colInfo[3], colInfo[4]);
          obj[titleArray[4]] = item.substring(colInfo[4], colInfo[5]);
          obj[titleArray[5]] = item.substr(colInfo[5]);
          if (obj[titleArray[1]].trim() != '') {
            arr.push({
              slot: obj[titleArray[0]].trim(),
              cardType: obj[titleArray[1]].trim(),
              realType: obj[titleArray[1]].trim(),
              numberOfPorts: 'N/A',
              softwateVersion: 'N/A',
              cardStatus: obj[titleArray[2]].trim(),
            });
          }
        });
        resolve(arr);
      } catch (error) {
        reject(error);
      }
    });
  }
  async getPortNumber(cardlist, oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '#' : systemName + '#',
        cardlist,
      };
      me.proxyFlag = this.options.proxyFlag;
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'PORT_NUMBER',
            oltHardVersion,
            view,
          },
          null,
          me,
          view.username==='root'
        );
        // resultArr.shift();
        for (let i = 0; i < cardlist.length; i++) {
          if (
            cardlist[i].cardStatus.toLocaleLowerCase().indexOf('normal') != -1
          ) {
            const ports = resultArr[i]
              .replace(/-{5,}/g, '|')
              .split('|')[2]
              .split('\n');
            ports.pop();
            ports.shift();
            cardlist[i].numberOfPorts = ports.length;
          }
        }
        resolve(cardlist);
      } catch (error) {
        reject(error);
      }
    });
  }
  async getUplinkPortInfo(ctx) {
    const maxRepetitions = 20;
    const oid1 = '1.3.6.1.2.1.31.1.1';
    const columns1 = [1];
    const oid2 = '1.3.6.1.2.1.2.2';
    const columns2 = [7];
    const p1 = new Promise(async (resolve, reject) => {
      const session = await createSession.call({
        ctx,
        proxyFlag : this.options.proxyFlag
      }, this.options.ip, this.options.community, this.options);
      session.tableColumns(
        oid1,
        columns1,
        maxRepetitions,
        function (error, table) {
          if (error) {
            return reject(error);
          }
          return resolve(table);
        }
      );
    });
    const p2 = new Promise(async (resolve, reject) => {
      const session = await createSession.call({
        ctx,
        proxyFlag : this.options.proxyFlag
      }, this.options.ip, this.options.community, this.options);
      session.tableColumns(
        oid2,
        columns2,
        maxRepetitions,
        function (error, table) {
          if (error) {
            return reject(error);
          }
          return resolve(table);
        }
      );
    });
    return Promise.all([p1, p2]);
  }
  async getOltTx_HW(ponPortsArray, oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
        ponPortsArray,
      };
      me.proxyFlag = this.options.proxyFlag;
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_PON_TX',
            oltHardVersion,
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resultArr.pop();
        const TxArr = [];
        for (let i = 0; i < resultArr.length; i++) {
          if (resultArr[i].indexOf('Failure') != -1) {
            TxArr.push({
              index: i,
              tx: 'N/A',
            });
          } else {
            const arr = resultArr[i].split('\n');
            for (let j = 0; j < arr.length; j++) {
              if (arr[j].indexOf('TX power(dBm)') != -1) {
                TxArr.push({
                  index: i,
                  tx: arr[j].replace('(dBm)', '|').split('|')[1].trim(),
                });
              }
            }
          }
        }
        resolve(TxArr);
      } catch (error) {
        reject(error);
      }
    });
  }
  async getPonTx(ponPortsArray, oltHardVersion, me) {
    try {
      me.proxyFlag = this.options.proxyFlag;
      const arr = await this.getOltTx_HW(ponPortsArray, oltHardVersion, me);
      ponPortsArray.forEach((item, index) => {
        item.TXPower = arr[index].tx;
      });
      return ponPortsArray;
    } catch (error) {
      return error;
    }
  }
  //已废弃
  async getUplinkStateAndSpeed(arr, uplinkport, oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
        arr,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_UPLINK_STATE_AND_SPEED',
            oltHardVersion,
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resultArr.shift();
        for (let i = 0; i < resultArr.length; i++) {
          const index = resultArr[i]
            .split('\n')[0]
            .replace('display board', '')
            .trim();
          const msg = resultArr[i]
            .replace(/-{5,}/g, '|')
            .split('|')[7]
            .split('\n');
          msg.pop();
          msg.shift();
          for (let j = 0; j < msg.length; j++) {
            const result = msg[j].replace(/\s+/g, '|').split('|');
            uplinkport['ethernet' + index + '/' + result[1]].Speed = result[2];
            if (result[10] == 'online') {
              uplinkport['ethernet' + index + '/' + result[1]].LinkStatus = 1;
            } else {
              uplinkport['ethernet' + index + '/' + result[1]].LinkStatus = 2;
            }
            // uplinkport["ethernet"+index+"/"+result[1]].LinkStatus = result[10]
          }
        }
        resolve(uplinkport);
      } catch (error) {
        reject(error);
      }
    });
  }
  //已废弃
  async getUplinkVlan(arr, oltHardVersion, me) {
    const key = Object.keys(arr);
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
        arr,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_UPLINK_TAGVLAN_AND_UNTAGVLAN',
            oltHardVersion,
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resultArr.shift();
        resultArr.forEach((item, index) => {
          if (item.indexOf('Failure') != -1) {
            arr[key[index]].untagArr = '';
            arr[key[index]].tagArr = '';
          } else {
            const result = [];
            const res = item
              .replace(/-{5,}/g, '|')
              .split('|')[1]
              .replace('\n', '')
              .trim()
              .replace(/\s{2,}/g, '|')
              .split('|');
            res.forEach(item => {
              if (item != '1') {
                result.push(item);
              }
            });
            const tagArr = result.toString();
            arr[key[index]].Tagvlan = tagArr;
            const untagArr = item
              .substring(
                item.indexOf('Native VLAN:') + 12,
                item.indexOf(systemName)
              )
              .trim();
            if (untagArr == '1') {
              arr[key[index]].UnTagvlan = '';
            } else {
              arr[key[index]].UnTagvlan = untagArr;
            }
          }
        });
        resolve(arr);
      } catch (error) {
        reject(error);
      }
    });
  }
  //
  async getUplinkAdminStatusAndVlan(port, oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
        port,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_UPLINK_ADMINSTATUS_AND_VLAN',
            oltHardVersion,
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const temp = Object.create(null);
        if (resultArr[0].indexOf('The port is not active') != -1) {
          temp.AdminStatus = 2;
        } else if (resultArr[0].indexOf('The port is active') != -1) {
          temp.AdminStatus = 1;
        }
        const res = resultArr[2]
          .replace(/-{5,}/g, '|')
          .split('|')[1]
          .replace('\n', '')
          .trim()
          .replace(/\s{2,}/g, '|')
          .split('|');
        res.shift();
        const tagArr = res.toString();
        temp.Tagvlan = tagArr;
        const untagArr = resultArr[2]
          .substring(
            resultArr[2].indexOf('Native VLAN:') + 12,
            resultArr[2].indexOf(systemName)
          )
          .trim();
        if (untagArr == '1') {
          temp.UnTagvlan = '';
        } else {
          temp.UnTagvlan = untagArr;
        }
        resolve(temp);
      } catch (error) {
        reject(error);
      }
    });
  }
  //已废弃
  async setUplink(
    portID,
    adminStatus,
    addvlan,
    UnTagvlan,
    oldUnTagvlan,
    removevlan,
    oltHardVersion,
    me
  ) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      if (adminStatus == 1) {
        var type = 'undo shutdown';
      } else if (adminStatus == 2) {
        var type = 'shutdown';
      }
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
        portID,
        type,
        addvlan,
        UnTagvlan,
        oldUnTagvlan,
        removevlan,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'SET_UPLINK',
            oltHardVersion,
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resolve(true);
      } catch (error) {
        reject(error);
      }
    });
  }
  //已废弃
  async getVlanTable(oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_VLAN',
            oltHardVersion,
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const msg = resultArr[0];
        const params = msg
          .replace(/.{5}More.*(\u001B\[37D)\s*\1/, '')
          .replace(/-{2,}/g, '|')
          .split('|');
        const str = params[2];
        const table = str.split('\n');
        const resultArray = [];
        table.forEach((item, index) => {
          const paramInfo = item.trim().replace(/\s+/g, '|').split('|');
          if (paramInfo.length > 1) {
            resultArray.push({
              VlanID: paramInfo[0],
              // Memo: paramInfo[0],
              vlanTagPort: '',
              vlanUntagPort: '',
              vlanRowStatus: '',
            });
          }
        });
        resolve(resultArray);
      } catch (error) {
        reject(error);
      }
    });
  }
  //已废弃
  async getVlanDesc(arr, oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
        arr,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_VLAN_DESC',
            oltHardVersion,
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resultArr.pop();
        for (var i = 0; i < resultArr.length; i++) {
          const msg = resultArr[i].split('\n');
          msg.forEach(item => {
            if (item.indexOf('VLAN description:') != -1) {
              arr[i].Memo = item.split(':')[1].trim();
            }
          });
        }
        for (let j = 0; j < resultArr.length; j++) {
          const msg2 = resultArr[j].replace(/-{5,}/g, '|').split('|');
          var tagArr = [];
          const untagArr = [];
          const uplinklist = {};
          if (msg2[2]) {
            const result = msg2[2]
              .replace(/(-{2,})\sMore.*(\u001B\[37D)\s*\2/g, '')
              .split('\n');
            result.pop();
            result.shift();
            result.forEach(item => {
              const uplinkResult = item
                .replace(/\s{2,}/g, '|')
                .split('|')[1]
                .replace(/\s/g, '');
              tagArr.push(uplinkResult);
            });
            uplinklist.tagArr = tagArr;
            uplinklist.untagArr = untagArr;
            arr[j].uplinklist = JSON.stringify(uplinklist);
          } else {
            uplinklist.tagArr = tagArr;
            uplinklist.untagArr = untagArr;
            arr[j].uplinklist = JSON.stringify(uplinklist);
          }
        }
        resolve(arr);
      } catch (error) {
        reject(error);
      }
    });
  }
  //已废弃
  async setVlanMemo(vlan, Memo, oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
        vlan,
        Memo,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'SET_VLAN_MEMO',
            oltHardVersion,
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resolve(true);
      } catch (error) {
        reject(error);
      }
    });
  }
  //已废弃
  async binduplink(binduplink, unbindlink, VlanID, oltHardVersion, me) {
    const binduplinkArr = [];
    const unbinduplinkArr = [];
    binduplink.forEach(item => {
      binduplinkArr.push({
        slot: item.split('/')[1].trim(),
        port: item.split('/')[2].trim(),
      });
    });
    unbindlink.forEach(item => {
      unbinduplinkArr.push({
        slot: item.split('/')[1].trim(),
        port: item.split('/')[2].trim(),
      });
    });

    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
        binduplinkArr,
        unbinduplinkArr,
        VlanID,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'VLAN_BIND_OR_UNBIND_UPLINK',
            oltHardVersion,
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resolve(true);
      } catch (error) {
        reject(error);
      }
    });
  }
  //已废弃
  async getmacTable_HW(oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'MAC_LIST',
            oltHardVersion,
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const msg = resultArr[0];
        const params = msg
          .replace(/.{5}More.*(\u001B\[37D)\s*\1/, '')
          .replace(/-{2,}/g, '|')
          .split('|');
        const str = params[2];
        const table = str.split('\n');
        const resultArray = [];
        table.forEach((item, index) => {
          const paramInfo = item.trim().replace(/\s+/g, '|').split('|');
          if (paramInfo.length > 1) {
            resultArray.push({
              VlanID: paramInfo[10].toString(),
              Mac: paramInfo[3].toString(),
              Type: paramInfo[4].toString(),
              PhysicalPort: 'ethernet' +
                paramInfo[5].toString() +
                paramInfo[6].toString() +
                paramInfo[7].toString(),
            });
          }
        });
        resolve(resultArray);
      } catch (error) {
        reject(error);
      }
    });
  }
  //已废弃
  async setVlans_HW(vlanStart, vlanEnd, oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
        vlanStart,
        vlanEnd,
      };
      try {
        if (vlanStart == vlanEnd) {
          const fn = function (msg) {
            if (msg.indexOf('Failure') != -1) {
              const msg1 = msg.substring(msg.indexOf('Failure'));
              const msg2 = msg1.substring(0, msg1.indexOf('\r\n'));
              return {
                result: false,
                message: msg2
              };
            }
            return {
              result: true
            };
          };
          const resultArr = await common.run_EX(
            addr, {
              oltType: 'HUAWEI',
              mountPoint: 'SETVLAN',
              oltHardVersion,
              view,
            },
            fn,
            me,
          view.username==='root'
          );
          if (resultArr.length != 0) {
            reject(resultArr[0]);
          } else {
            resolve(true);
          }
        } else {
          const resultArr = await common.run_EX(
            addr, {
              oltType: 'HUAWEI',
              mountPoint: 'SETVLAN_BULK',
              oltHardVersion,
              view,
            },
            null,
            me,
          view.username==='root'
          );
          resolve(true);
        }
      } catch (error) {
        reject(error);
      }
    });
  }
  async getLineProfile(oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: 'rzadmin1',
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_LINEPROFILE',
            oltHardVersion,
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const msg = resultArr[0];
        const arr = msg
          .replace(/.{5}More.*(\u001B\[37D)\s*\1/, '')
          .replace(/-{2,}/g, '|')
          .split('|');
        const str = arr[2];
        const table = str.split('\n');
        table.pop();
        table.shift();
        const resultArray = [];
        table.forEach(item => {
          const a = item.trim().replace(/\s+/g, '|').split('|');
          resultArray.push({
            PID: a[0],
            Pname: a[1],
          });
        });
        resolve(resultArray);
      } catch (error) {
        reject(error);
      }
    });
  }
  
  async getLineProfileMessage(oltHardVersion, arr, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        arr,
        prompt: this.options.systemName,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_LINEPROFILEMESSAGE',
            oltHardVersion,
            view,
          },
          null,
          me,
          view.username==='root'
        );
        let arr = new Map();
        resultArr.forEach(response=>{
          if(/Gem.*\s+Index/ig.test(response)){
            try {
              let rows = response.split('\n');
            let lineProfileDetail = {
              profileID:'',
              profileName:'',
              tcont:{},
              gemport:{}
            }
            let currentTcont ='';
            rows.forEach((row,index)=>{
              let mappingModeGroup = /Mapping mode\s+:(\w+)$/i.exec(row)
              if(mappingModeGroup){
                let [str,mode] = mappingModeGroup;
                if(!/vlan/i.test(mode)){
                  throw new Error('不支持非VLAN模式')
                }
              }
              let idGroup = /^\s+Profile-ID.*:(\w+)$/i.exec(row);
              if(idGroup){
                let [str,id] = idGroup;
                lineProfileDetail.profileID=id;
                return;
              }
              let nameGroup = /Profile-name.*:(\w+)$/i.exec(row);
              if(nameGroup){
                let [str,name] = nameGroup;
                lineProfileDetail.profileName=name;
                return;
              }
              let tcontGroup = /T-CONT\s+(\w+)>\s+DBA\s+Profile-ID:(\w+)/i.exec(row)
              if(tcontGroup){
                let [str,tcont,dbaID] = tcontGroup;
                currentTcont = tcont;
                lineProfileDetail.tcont[tcont] = {
                  tcont,
                  dbaID
                }
              }
              let gemGroup = /Gem.*\s+Index\s+(\w)>/i.exec(row)
              if(gemGroup){
                let [str,gemNo] = gemGroup;
                let vlanRow = rows[index+8];
                let vlan = vlanRow&&vlanRow.substr(12,4).trim()
                lineProfileDetail.gemport[gemNo] = {
                  gemport:gemNo,
                  gVLAN:vlan,
                  tcont:currentTcont,
                  dbaProfileID:lineProfileDetail.tcont[currentTcont].dbaID
                }
              }
            })
            for(let gemNo in lineProfileDetail.gemport){
              arr.has(lineProfileDetail.profileName)?arr.get(lineProfileDetail.profileName).push(lineProfileDetail.gemport[gemNo]):arr.set(lineProfileDetail.profileName,[lineProfileDetail.gemport[gemNo]])
            }
            } catch (error) {
              console.log(error)
            }
          }
        })
        
        resolve(arr);
      } catch (error) {
        reject(error);
      }
    });
  }
  //已废弃
  async getSrvProfile(oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: 'rzadmin1',
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
        prompt_1: '#',
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_SRVPROFILE',
            oltHardVersion,
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const msg = resultArr[0];
        const lines = msg
          .replace(/(-{2,})\sMore.*(\u001B\[37D)\s*\2/g, '')
          .split('\n');
        const titleArray = ['Profile-ID', 'Profile-name', 'Binding times'];
        const colInfo = [];
        const title = lines.filter(
          value => value.indexOf(titleArray[0]) != -1
        );
        titleArray.forEach(titleItem =>
          colInfo.push(title[0].indexOf(titleItem))
        );
        const contents = lines.filter(
          value =>
          value.indexOf('---') == -1 &&
          value.indexOf('display') == -1 &&
          value.indexOf('Total') == -1 &&
          value.indexOf('config') == -1 &&
          value.indexOf(titleArray[0]) == -1 &&
          value.indexOf('>') == -1
        );
        const arr = [];
        contents.forEach(item => {
          arr.push({
            profileID: item.substring(colInfo[0], colInfo[1]).trim(),
            profileName: item.substring(colInfo[1], colInfo[2]).trim(),
          });
        });
        resolve(arr);
      } catch (error) {
        reject(error);
      }
    });
  }
  async getRunningConfig(oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const addr = this.options.ip + ':' + this.options.tPort;

      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '#' : systemName + '#',
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_RUNNINGCONFIG',
            oltHardVersion,
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const msg = resultArr[0];
        const lineprofileArr = msg.match(/ont-lineprofile[\s\Sa-zA-Z0-9]+?quit/g);
        const lineProfiles = [];
        if (lineprofileArr.length > 0) {
          lineprofileArr.forEach(lineStr => {
            let lineProfile = {
              id: '',
              name: '',
              type: '',
              tcontArr: [],
              tcontToDba: new Map(),
              gemArr: [],
              gemToTcont: new Map(),
              gemToVlan: new Map(),
            }
            let arr = lineStr.split('\n')
            if (arr.length > 0) {
              let describe = arr[0];
              let obj = this.ParseDescribe(describe);
              if (obj) {
                lineProfile.id = obj.id;
                lineProfile.name = obj.name;
                lineProfile.type = obj.type;
              } else {
                return;
              }
              arr.forEach(str => {
                let info = this.ParseTcont(str);
                if (info) {
                  lineProfile.tcontArr.push(info.tcont);
                  lineProfile.tcontToDba.set(info.tcont, info);
                }
                info = this.ParseGem(str);
                if (info) {
                  lineProfile.gemArr.push(info.gemIndex);
                  lineProfile.gemToTcont.set(info.gemIndex, info)
                }
                info = this.ParseGemMapping(str);
                if (info) {
                  lineProfile.gemToVlan.set(info.gemIndex, info)
                }
              })
            } else {
              return;
            }
            lineProfiles.push(lineProfile)
          })
        }
        resolve(lineProfiles);
      } catch (error) {
        reject(error);
      }
    });
  }
  ParseDescribe(describe) {
    let reg = /ont-lineprofile\s+([\w]+)\s+profile-id\s+(\d+)\s+profile-name\s+"(\w+)"/
    let groups = describe.match(reg)
    if (groups && groups.length === 4) {
      return {
        type: groups[1],
        id: groups[2],
        name: groups[3],
      }
    }
    return null;
  }
  ParseTcont(str) {
    let reg = /.*tcont\s+(\d+)\s+dba-profile-id\s+(\d+)/
    let groups = str.match(reg);
    if (groups && groups.length === 3) {
      return {
        tcont: groups[1],
        dbaProfileID: groups[2],
      }
    }
    return null;
  }
  ParseGem(str) {
    let reg = /.*gem\s+add\s+(\d+)\s+(\w+)\s+tcont\s+(\d)+/
    let groups = str.match(reg);
    if (groups && groups.length === 4) {
      return {
        gemIndex: groups[1],
        gemType: groups[2],
        tcont: groups[3],
      }
    }
    return null;
  }
  ParseGemMapping(str) {
    let reg = /.*gem\s+mapping\s+(\d+)\s+(\d+)\s+vlan\s+(\d+)/
    let groups = str.match(reg);
    if (groups && groups.length === 4) {
      return {
        gemIndex: groups[1],
        mappingIndex: groups[2],
        vlan: groups[3],
      }
    }
    return null;
  }
  async getonufind_HW(oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const addr = this.options.ip + ':' + this.options.tPort;

      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'ONU_FIND',
            oltHardVersion,
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const msg = resultArr[0];
        const arr = msg
          .replace(/.{5}More.*(\u001B\[37D)\s*\1/, '')
          .replace(/-{5,}/g, '|')
          .split('|');
        arr.shift();
        arr.pop();
        const resultArray = [];
        arr.forEach((item, index) => {
          const itemParams = item.replace(/\n/g, '|').split('|');
          let ONTSN = itemParams[3].split(':')[1];
          if (ONTSN.indexOf('(') != -1) {
            var ONTSNIndex = ONTSN.indexOf('(');
          } else {
            var ONTSNIndex = ONTSN.indexOf('Password');
          }
          ONTSN = ONTSN.substring(0, ONTSNIndex).trim();
          ONTSN = transSN(ONTSN);
          resultArray.push({
            PONindex: itemParams[2].split(':')[1].trim(),
            SN: ONTSN,
            state: '',
          });
        });
        resolve(resultArray);
      } catch (error) {
        reject(error);
      }
    });
  }
  async setONU(
    PONindex,
    ONUindex,
    SN,
    lineProfile,
    srvProfile,
    name,
    acsVlan,
    lineProfileBusiness,
    me
  ) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const F = PONindex.split('/')[0];
      const S = PONindex.split('/')[1];
      const P = PONindex.split('/')[2];
      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        F,
        S,
        P,
        ONUindex,
        SN,
        PONindex,
        lineProfile,
        srvProfile,
        name,
        acsVlan,
        arr: lineProfileBusiness,
      };
      try {
        const fn = function (msg) {
          if (msg.indexOf('The ONT ID has already existed') != -1) {
            return {
              result: false,
              message: 'The ONT ID has already existed'
            };
          } else if (msg.indexOf('SN already exists') != -1) {
            return {
              result: false,
              message: 'SN already exists'
            };
          } else if (msg.indexOf('The line profile does not exist') != -1) {
            return {
              result: false,
              message: 'The line profile does not exist',
            };
          } else if (msg.indexOf('The service profile does not exist') != -1) {
            return {
              result: false,
              message: 'The service profile does not exist',
            };
          } else if (msg.indexOf('The GEM index does not exist') != -1) {
            return {
              result: false,
              message: 'The GEM index does not exist'
            };
          } else if (msg.indexOf('VLAN does not exist') != -1) {
            return {
              result: false,
              message: 'VLAN does not exist'
            };
          } else if (msg.indexOf('The traffic table does not exist') != -1) {
            return {
              result: false,
              message: 'The traffic table does not exist',
            };
          } else if (msg.indexOf('Failure') != -1) {
            return {
              result: false,
              message: msg.substring(msg.indexOf('Failure:') + 8).trim(),
            };
          }
          return {
            result: true
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'CREATE_ONUFIND',
            oltHardVersion: 'NONE',
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        if (resultArr.length != 0) {
          resolve(resultArr);
        } else {
          resolve(true);
        }
      } catch (error) {
        reject(error);
      }
    });
  }
  async deleteONU(PONindex, ONUindex, serviceport, oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const addr = this.options.ip + ':' + this.options.tPort;
      const F = PONindex.split('/')[0]; // 框架
      const S = PONindex.split('/')[1]; // 板卡
      const P = PONindex.split('/')[2]; // pon口
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
        F,
        S,
        P,
        ONUindex,
        serviceport,
      };
      try {
        const fn = function (msg) {
          if (msg.indexOf('Failure') != -1) {
            return {
              result: false,
              message: msg
                .substring(msg.indexOf('Failure:') + 8, msg.indexOf(systemName))
                .trim(),
            };
          }
          return {
            result: true
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'DELETE_ONU',
            oltHardVersion,
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        if (resultArr.length != 0) {
          reject(resultArr);
        } else {
          resolve(true);
        }
      } catch (error) {
        reject(error);
      }
    });
  }
  async getOnuList(oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'ONU_LIST',
            oltHardVersion,
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const msg = resultArr[0];
        const params = msg
          .replace(/.{5}More.*(\u001B\[37D)\s*\1/, '')
          .split('F/S/P');
        params.shift();
        const resultArray = [];
        for (let i = 0; i < params.length; i = i + 2) {
          let paramInfo = params[i].replace(/-{5,}/g, '|').split('|');
          paramInfo = paramInfo[1].split('0/');
          paramInfo.shift();
          for (let j = 0; j < paramInfo.length; j++) {
            const data = paramInfo[j].replace(/\s{2,}/g, '|').split('|');
            const S = data[0].split('/')[0].trim();
            const P = data[0].split('/')[1].trim();
            resultArray.push({
              S,
              P,
              ONUindex: data[1],
            });
          }
        }
        resolve(resultArray);
      } catch (error) {
        reject(error);
      }
    });
  }
  async getONUDetailInfo(onuArr, oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
        onuArr,
      };
      try {
        const resultArray = [];
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_DETAIL_INFO',
            oltHardVersion,
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resultArr.forEach(item => {
          const PONindex = item
            .substring(item.indexOf('F/S/P'), item.indexOf('ONT-ID'))
            .split(':')[1]
            .trim();
          const ONUindex = item
            .substring(item.indexOf('ONT-ID'), item.indexOf('Control flag'))
            .split(':')[1]
            .trim();
          const onlyindex = PONindex + ':' + ONUindex;
          const S = PONindex.split('/')[1];
          const P = PONindex.split('/')[2];
          const stateResult = item
            .substring(item.indexOf('Run state'), item.indexOf('Config state'))
            .split(':')[1]
            .trim();
          if (stateResult == 'online') {
            var state = 'working';
          } else if (stateResult == 'offline') {
            var state = 'OffLine';
          } else {
            var state = stateResult;
          }
          let SN = item
            .substring(item.indexOf('SN'), item.indexOf('Management mode'))
            .split(':')[1]
            .trim();
          SN = SN.substring(0, SN.indexOf('(')).trim();
          SN = transSN(SN);
          const ONUname = item
            .substring(
              item.indexOf('Description'),
              item.indexOf('Last down cause')
            )
            .split(':')[1]
            .trim();
          resultArray.push({
            ONUname,
            PONindex,
            ONUindex,
            SN,
            onlyindex,
            state,
            S,
            P,
          });
        });
        resolve(resultArray);
      } catch (error) {
        reject(error);
      }
    });
  }
  //已废弃
  async deleteVlan_HW(vlanID, oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
        vlanID,
      };
      try {
        const fn = function (msg) {
          if (msg.indexOf('Failure') != -1) {
            return {
              result: false,
              message: msg
                .substring(msg.indexOf('Failure:') + 8, msg.indexOf(systemName))
                .trim(),
            };
          }
          return {
            result: true
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'DELETE_VLAN',
            oltHardVersion,
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        if (resultArr.length != 0) {
          reject(resultArr);
        } else {
          resolve(true);
        }
      } catch (error) {
        reject(error);
      }
    });
  }
  async getOnuServicePort(PONindex, ONUindex, oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
        PONindex,
        ONUindex,
      };
      try {
        const serviceport = [];
        const fn = function (msg) {
          if (msg.indexOf('Failure') != -1) {
            return {
              result: false,
              message: msg
                .substring(msg.indexOf('Failure:') + 8, msg.indexOf(systemName))
                .trim(),
            };
          }
          const servicePortArr = msg
            .replace(/-{5,}/g, '|')
            .split('|')[2]
            .trim()
            .split('\r\n');
          for (let i = 0; i < servicePortArr.length; i++) {
            serviceport.push(
              servicePortArr[i].trim().replace(/\s+/g, '|').split('|')[0]
            );
          }
          return {
            result: true
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_ONU_SERVICEPORT',
            oltHardVersion,
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        console.log(resultArr);
        if (resultArr.length != 0) {
          resolve('');
        } else {
          resolve(serviceport);
        }
      } catch (error) {
        reject(error);
      }
    });
  }
  async saveOlt(oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'SAVE',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resolve(true);
      } catch (error) {
        reject(error);
      }
    });
  }
  async rebootOlt(oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'REBOOT',
            oltHardVersion,
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resolve(true);
      } catch (error) {
        reject(error);
      }
    });
  }
  async activeOlt(oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'ACTIVE',
            oltHardVersion,
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resolve(true);
      } catch (error) {
        reject(error);
      }
    });
  }

  async oltBackUp(id, oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const result = {
        msg: '',
        flag: false,
      };
      const addr = this.options.ip + ':' + this.options.tPort;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const ftphost = common.getIP();
      me.ctx.logger.error(ftphost);
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
        host: me.app.config.ftpIP,
        ftpName: me.app.config.ftpUsername,
        ftpPassword: me.app.config.ftpPassword,
        fileName: id + '_startrun.cfg',
      };
      try {
        const fn = function (msg) {
          if (msg.indexOf('System') != -1) {
            return {
              result: false,
              message: msg.substring(msg.indexOf('System')).trim(),
            };
          }
          return {
            result: true
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'BACKUP',
            oltHardVersion,
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        if (resultArr.length != 0) {
          result.msg = 'backup fail,' + resultArr[0];
          result.flag = false;
          resolve(result);
        } else {
          result.msg = 'backup successful';
          result.flag = true;
          resolve(result);
        }
      } catch (error) {
        result.msg = 'backup fail,' + error;
        result.flag = false;
        resolve(result);
      }
    });
  }
  async oltRestore(id, oltHardVersion, fileName, me) {
    const result = {
      flag: false,
      data: '',
    };
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
        host: me.app.config.ftpIP,
        ftpName: me.app.config.ftpUsername,
        ftpPassword: me.app.config.ftpPassword,
        fileName,
      };
      try {
        const fn = function (msg) {
          if (msg.indexOf('System') != -1) {
            return {
              result: false,
              message: msg.substring(msg.indexOf('System')).trim(),
            };
          } else if (msg.indexOf('Failure') != -1) {
            return {
              result: false,
              message: msg
                .substring(msg.indexOf('Failure:') + 8, msg.indexOf(systemName))
                .replace('\r', '')
                .replace('\n', '')
                .trim(),
            };
          } else if (msg.indexOf('Failure cause') != -1) {
            const a = msg.indexOf(msg.indexOf('Failure cause:') + 14);
            return {
              result: false,
              message: a
                .substring(0, a.indexOf(systemName))
                .replace('\r', '')
                .replace('\n', '')
                .trim(),
            };
          }
          return {
            result: true
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'RESTORE',
            oltHardVersion,
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        if (resultArr.length != 0) {
          result.flag = false;
          result.data = 'upload fail,' + resultArr[0];
          resolve(result);
        } else {
          result.flag = true;
          result.data = 'upload successful';
          resolve(result);
        }
      } catch (error) {
        result.flag = false;
        result.data = 'upload fail,' + error;
        resolve(result);
      }
    });
  }
  async oltInit(vlan, oltHardVersion, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const systemName =
        this.options.systemName == '' ?
        getSystemName() :
        this.options.systemName;
      const view = {
        username: this.options.username,
        password: this.options.password,
        prompt: systemName.indexOf('|') != -1 ?
          systemName.split('|').join('>|') + '>' : systemName + '>',
        vlan,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'OLT_INIT',
            oltHardVersion,
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resolve(true);
      } catch (error) {
        reject(error);
      }
    });
  }
  //----------------------------------------------------------------------------------
  // 获取ontStatus
  async HWTestConnection(me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = `${this.options.ip}:${this.options.tPort}`;
      const fn = function (message) {
        if (message.indexOf('Username or password invalid') != -1) {
          return {
            result: false,
            message,
          };
        } else if (
          message.indexOf('Reenter times have reached the upper limit') != -1
        ) {
          return {
            result: false,
            message,
          };
        }
        return {
          result: true,
          message: '',
        };
      };
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_VERSION',
            oltHardVersion: 'NONE',
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        if (
          resultArr.length > 0 &&
          (resultArr[0].indexOf('Username or password invalid') != -1 ||
            resultArr[0].indexOf(
              'Reenter times have reached the upper limit'
            ) != -1)
        ) {
          return resolve(false);
        }
        resolve(true);
      } catch (error) {
        resolve(false);
      }
    });
  }
  // SNMP获取systemName
  async getOltSystemName(ctx) {
    return new Promise(async (resolve, reject) => {
      const olt = {
        systemName: '',
        runningTime: '',
      };
      const oids = [
        '1.3.6.1.2.1.1.5.0', // systemName
        '1.3.6.1.2.1.1.3.0', // running time
      ];
      const session = await createSession.call({
        ctx,
        proxyFlag : this.options.proxyFlag
      }, this.options.ip, this.options.community, this.options);
      session.get(oids, function (error, varbinds) {
        if (error) {
          reject(error);
        } else {
          for (let i = 0; i < varbinds.length; i++) {
            if (!snmp.isVarbindError(varbinds[i])) {
              if (varbinds[i].oid == oids[0]) {
                olt.systemName = varbinds[i].value.toString();
              }
              if (varbinds[i].oid == oids[1]) {
                olt.runningTime = varbinds[i].value.toString();
              }
            }
          }
          resolve(olt);
        }
        session.close();
      });
    });
  }
  // 设置 RZAdmin
  async setRZAdmin(me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        username: this.options.username,
        password: this.options.password,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'CREATE_RZADMIN',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resolve(true);
      } catch (error) {
        reject(error);
      }
    });
  }
  // 获取version
  async getOltVersion(me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_VERSION',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const result = {};
        result.oltHardwareVersion = resultArr[0]
          .substring(
            resultArr[0].indexOf('PRODUCT :') + 9,
            resultArr[0].indexOf('Active')
          )
          .trim();
        result.oltSoftwareVersion = resultArr[0]
          .substring(
            resultArr[0].indexOf('VERSION :') + 9,
            resultArr[0].indexOf('PATCH')
          )
          .trim();
        result.oltHardVersion = resultArr[0]
          .substring(
            resultArr[0].indexOf('PRODUCT :') + 9,
            resultArr[0].indexOf('Active')
          )
          .trim();
        const maincard = resultArr[0]
          .replace(/-{5,}/g, '|')
          .split('|')[1]
          .substring(
            resultArr[0]
            .replace(/-{5,}/g, '|')
            .split('|')[1]
            .indexOf('Current Program Area :') + 22,
            resultArr[0]
            .replace(/-{5,}/g, '|')
            .split('|')[1]
            .indexOf('Current Data Area :')
          )
          .trim();
        if (result.oltHardwareVersion == 'MA5680T' && maincard == 'Area A') {
          result.MCIndex = 8;
        } else if (
          result.oltHardwareVersion == 'MA5680T' &&
          maincard == 'Area B'
        ) {
          result.MCIndex = 7;
        }
        resolve(result);
      } catch (error) {
        reject(error);
      }
    });
  }
  // 获取oltInformation
  async getOltInformation(MCIndex, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        MCIndex,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_OLTINFORMATION',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const result = {};
        (result.MCIndex = MCIndex),
        (result.cpuUsage = resultArr[0]
          .substring(
            resultArr[0].indexOf('CPU occupancy:') + 14,
            resultArr[0].indexOf(view.prompt)
          )
          .trim());
        result.memoryUsage = resultArr[1]
          .substring(
            resultArr[1].indexOf('Memory occupancy:') + 17,
            resultArr[1].indexOf(view.prompt)
          )
          .trim();
        result.systemTime = resultArr[2]
          .substring(
            resultArr[2].indexOf('display time') + 12,
            resultArr[2].indexOf(view.prompt)
          )
          .trim();
        resolve(result);
      } catch (error) {
        reject(error);
      }
    });
  }
  // 获取oltTemperature
  async getOltTemperature(MCIndex, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        MCIndex,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_OLTTEMPERATURE',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const oltTemperature = resultArr[0]
          .substring(
            resultArr[0].indexOf('The temperature of the board:') + 29,
            resultArr[0].indexOf('C')
          )
          .trim();
        resolve(oltTemperature);
      } catch (error) {
        reject(error);
      }
    });
  }
  // 获取CardInformation
  async getCardInformation(me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_CARDINFORMATION',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const msg = resultArr[0];
        const lines = msg
          .replace(/(-{2,})\sMore.*(\u001B\[37D)\s*\2/g, '')
          .split('\n');
        const titleArray = [
          'SlotID',
          'BoardName',
          'Status',
          'SubType0',
          'SubType1',
          'Online/Offline',
        ];
        const colInfo = [];
        const title = lines.filter(
          value => value.indexOf(titleArray[0]) != -1
        );
        titleArray.forEach(titleItem =>
          colInfo.push(title[0].indexOf(titleItem))
        );
        const contents = lines.filter(
          value =>
          value.indexOf('---') == -1 &&
          value.indexOf('display') == -1 &&
          value.indexOf('Total') == -1 &&
          value.indexOf('config') == -1 &&
          value.indexOf(titleArray[0]) == -1 &&
          value.indexOf('>') == -1
        );
        const arr = [];
        contents.forEach(item => {
          const slot = item.substring(colInfo[0], colInfo[1]).trim();
          const type = item.substring(colInfo[1], colInfo[2]).trim();
          const status = item.substring(colInfo[2], colInfo[3]).trim();
          if (type != '') {
            arr.push({
              slot,
              type,
              status,
            });
          }
        });
        resolve(arr);
      } catch (error) {
        reject(error);
      }
    });
  }
  // 获取PonPorts和UplinkPorts
  async getPonPortsAndUplinkPorts(ctx) {
    const maxRepetitions = 20;
    const oid1 = '1.3.6.1.2.1.31.1.1';
    const columns1 = [1];
    const oid2 = '1.3.6.1.2.1.2.2';
    const columns2 = [5, 7, 8];
    const p1 = new Promise(async (resolve, reject) => {
      const session = await createSession.call({
        ctx,
        proxyFlag : this.options.proxyFlag
      }, this.options.ip, this.options.community, this.options);
      session.tableColumns(
        oid1,
        columns1,
        maxRepetitions,
        function (error, table) {
          if (error) {
            return reject(error);
          }
          return resolve(table);
        }
      );
    });
    const p2 = new Promise(async (resolve, reject) => {
      const session = await createSession.call({
        ctx,
        proxyFlag : this.options.proxyFlag
      }, this.options.ip, this.options.community, this.options);
      session.tableColumns(
        oid2,
        columns2,
        maxRepetitions,
        function (error, table) {
          if (error) {
            return reject(error);
          }
          return resolve(table);
        }
      );
    });
    return Promise.all([p1, p2]);
  }
  // 获取onuprofile
  async getSrvProfileList(me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_SRVPROFILELIST',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const msg = resultArr[0];
        const lines = msg
          .replace(/(-{2,})\sMore.*(\u001B\[37D)\s*\2/g, '')
          .split('\n');
        const titleArray = ['Profile-ID', 'Profile-name', 'Binding times'];
        const colInfo = [];
        const title = lines.filter(
          value => value.indexOf(titleArray[0]) != -1
        );
        titleArray.forEach(titleItem =>
          colInfo.push(title[0].indexOf(titleItem))
        );
        const contents = lines.filter(
          value =>
          value.indexOf('---') == -1 &&
          value.indexOf('display') == -1 &&
          value.indexOf('Total') == -1 &&
          value.indexOf('config') == -1 &&
          value.indexOf(titleArray[0]) == -1 &&
          value.indexOf('>') == -1
        );
        const arr = [];
        contents.forEach(item => {
          arr.push({
            // PID: item.substring(colInfo[0], colInfo[1]).trim(),
            Pname: item.substring(colInfo[1], colInfo[2]).trim(),
          });
        });
        resolve(arr);
      } catch (error) {
        reject(error);
      }
    });
  }
  // 获取dbaprofile
  async getDBAProfileList(me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        // username: this.options.RZUsername,
        username: 'rzadmin1',
        password: this.options.RZPassword,
        prompt: this.options.systemName,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_DBAPROFILELIST',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const msg = resultArr[0];
        const lines = msg
          .replace(/(-{2,})\sMore.*(\u001B\[37D)\s*\2/g, '')
          .split('\n');
        const titleArray = [
          'Profile-ID',
          'type',
          'Bandwidth',
          'Fix',
          'Assure',
          'Max',
          'Bind',
        ];
        const colInfo = [];
        const title = lines.filter(
          value => value.indexOf(titleArray[0]) != -1
        );
        titleArray.forEach(titleItem =>
          colInfo.push(title[0].indexOf(titleItem))
        );
        const contents = lines.filter(
          value =>
          value.indexOf('---') == -1 &&
          value.indexOf('compensation') == -1 &&
          value.indexOf('display') == -1 &&
          value.indexOf('Total') == -1 &&
          value.indexOf('config') == -1 &&
          value.indexOf(titleArray[0]) == -1 &&
          value.indexOf('>') == -1
        );
        const arr = [];
        contents.forEach(item => {
          arr.push({
            index: item.substring(colInfo[0], colInfo[1]).trim(),
          });
        });
        resolve(arr);
      } catch (error) {
        reject(error);
      }
    });
  }
  async getDBAProfile(list, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        // username: this.options.RZUsername,
        username: 'rzadmin1',
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        list,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_DBAPROFILE',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const arr = [];
        // resultArr.shift();
        let nameReg = /Profile-name\s*:\s*(.+)\s*$/i;
        let idReg = /Profile-ID\s*:\s*(.+)\s*$/i;
        let maxReg = /Max.*:\s*(.+)\s*$/i;
        let fbwReg = /Fix.*:\s*(.+)\s*$/i;
        let abwReg = /Assure.*:\s*(.+)\s*$/i;
        let typeReg = /type\s*:\s*(.+)\s*$/i;
        resultArr.forEach(response=>{
          const rows = response.split('\n');
          let obj = {}
          rows.forEach(row=>{
            let nameGroup = nameReg.exec(row);
            if(nameGroup){
              let [str,name] = nameGroup;
              obj.name=name&&name.trim();
              return;
            }
            let idGroup = idReg.exec(row);
            if(idGroup){
              let [str,id] = idGroup;
              obj.id = id&&id.trim();
              return;
            }
            let typeGroup = typeReg.exec(row)
            if(typeGroup){
              let [str,type] = typeGroup;
              obj.type=type&&type.trim();
              return;
            }
            let fbwGroup = fbwReg.exec(row);
            if(fbwGroup){
              let [str,fbw] = fbwGroup;
              obj.fbw = fbw&&fbw.trim();
              return;
            }
            let abwGroup = abwReg.exec(row);
            if(abwGroup){
              let [str,abw] = abwGroup;
              obj.abw=abw&&abw.trim();
              return;
            }
            let maxGroup = maxReg.exec(row);
            if(maxGroup){
              let [str,max] = maxGroup;
              obj.max = max&&max.trim();
              return;
            }
          })
          arr.push(obj);
        })
        // for (let i = 0; i < resultArr.length; i++) {
        //   const name = resultArr[i]
        //     .substring(
        //       resultArr[i].indexOf('Profile-name'),
        //       resultArr[i].indexOf('Profile-ID')
        //     )
        //     .split(':')[1]
        //     .replace('[Default&Reserve]', '')
        //     .trim();
        //   const max = resultArr[i]
        //     .substring(
        //       resultArr[i].indexOf('Max(kbps)'),
        //       resultArr[i].indexOf('Additional-bandwidth')
        //     )
        //     .split(':')[1]
        //     .trim();
        //   const fbw = resultArr[i]
        //     .substring(
        //       resultArr[i].indexOf('Fix(kbps)'),
        //       resultArr[i].indexOf('Assure(kbps)')
        //     )
        //     .split(':')[1]
        //     .trim();
        //   const abw = resultArr[i]
        //     .substring(
        //       resultArr[i].indexOf('Assure(kbps)'),
        //       resultArr[i].indexOf('Max(kbps)')
        //     )
        //     .split(':')[1]
        //     .trim();
        //   const type = resultArr[i]
        //     .substring(
        //       resultArr[i].indexOf('type'),
        //       resultArr[i].indexOf('Bandwidth compensation')
        //     )
        //     .split(':')[1]
        //     .trim();
        //   arr.push({
        //     name,
        //     max,
        //     type,
        //     fbw,
        //     abw,
        //   });
        // }
        resolve(arr);
      } catch (error) {
        reject(error);
      }
    });
  }
  // 获取lineprofile
  async getOltLineProfile(me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        // username: this.options.RZUsername,
        username: 'rzadmin1',
        password: this.options.RZPassword,
        prompt: this.options.systemName,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_LINEPROFILELIST',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const msg = resultArr[0];
        const lines = msg
          .replace(/(-{2,})\sMore.*(\u001B\[37D)\s*\2/g, '')
          .split('\n');
        const titleArray = ['Profile-ID', 'Profile-name', 'Binding times'];
        const colInfo = [];
        const title = lines.filter(
          value => value.indexOf(titleArray[0]) != -1
        );
        titleArray.forEach(titleItem =>
          colInfo.push(title[0].indexOf(titleItem))
        );
        const contents = lines.filter(
          value =>
          value.indexOf('---') == -1 &&
          value.indexOf('compensation') == -1 &&
          value.indexOf('display') == -1 &&
          value.indexOf('Total') == -1 &&
          value.indexOf('config') == -1 &&
          value.indexOf(titleArray[0]) == -1 &&
          value.indexOf('>') == -1
        );
        const arr = [];
        contents.forEach(item => {
          arr.push({
            index: item.substring(colInfo[0], colInfo[1]).trim(),
            name: item.substring(colInfo[1], colInfo[2]).trim(),
          });
        });
        resolve(arr);
      } catch (error) {
        reject(error);
      }
    });
  }
  //获取lineprofile的详细信息
  async getOltLineProfileDetail(lines,me){
    return new Promise(async (resolve, reject) =>{
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        // username: this.options.RZUsername,
        username: 'rzadmin1',
        password: this.options.RZPassword,
        prompt: this.options.systemName,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_LINEPROFILELIST_DETAIL',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resolve(resultArr)
      } catch (error) {
        reject(error);
      }
    })
  }
  // 获取vlan
  async getOltVlan(me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        // username: this.options.RZUsername,
        username: 'rzadmin1',
        password: this.options.RZPassword,
        prompt: this.options.systemName,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_VLANLIST',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const msg = resultArr[0];
        const lines = msg
          .replace(/(-{2,})\sMore.*(\u001B\[37D)\s*\2/g, '')
          .split('\n');
        const titleArray = [
          'VLAN',
          'Type',
          'Attribute',
          'STND-Port NUM',
          'SERV-Port NUM',
          'VLAN-Con NUM',
        ];
        const colInfo = [];
        const title = lines.filter(
          value => value.indexOf(titleArray[0]) != -1
        );
        titleArray.forEach(titleItem =>
          colInfo.push(title[0].indexOf(titleItem))
        );
        const contents = lines.filter(
          value =>
          value.indexOf('---') == -1 &&
          value.indexOf('Command') == -1 &&
          value.indexOf('Note') == -1 &&
          value.indexOf(this.options.systemName) == -1 &&
          value.indexOf('display') == -1 &&
          value.indexOf('Total') == -1 &&
          value.indexOf('config') == -1 &&
          value.indexOf(titleArray[0]) == -1 &&
          value.indexOf('>') == -1
        );
        const arr = [];
        contents.forEach(item => {
          arr.push({
            VlanID: item.substring(colInfo[0], colInfo[1]).trim(),
          });
        });
        resolve(arr);
      } catch (error) {
        reject(error);
      }
    });
  }
  //获取mac
  async getOltMac(me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        // username: this.options.RZUsername,
        username: 'rzadmin1',
        password: this.options.RZPassword,
        prompt: this.options.systemName,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_MACLIST',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const msg = resultArr[0];
        const lines = msg
          .replace(/(-{2,})\sMore.*(\u001B\[37D)\s*\2/g, '')
          .split('\n');
        const titleArray = [
          'SRV-P',
          'BUNDLE',
          'TYPE',
          'MAC',
          'MAC TYPE',
          'F /S /P',
          'VPI',
          'VCI',
          'VLAN ID'
        ];
        const colInfo = [];
        const title = lines.filter(
          value => value.indexOf(titleArray[0]) != -1
        );
        titleArray.forEach(titleItem =>
          colInfo.push(title[0].indexOf(titleItem))
        );
        const contents = lines.filter(
          value =>
          value.indexOf('---') == -1 &&
          value.indexOf('Command') == -1 &&
          value.indexOf('Note') == -1 &&
          value.indexOf(this.options.systemName) == -1 &&
          value.indexOf('display') == -1 &&
          value.indexOf('Total') == -1 &&
          value.indexOf('config') == -1 &&
          value.indexOf(titleArray[0]) == -1 &&
          value.indexOf('>') == -1 &&
          value.indexOf('INDEX') == -1 &&
          value.indexOf('It') == -1 &&
          value.indexOf('VPI') == -1 &&
          value.indexOf('v/e') == -1 &&
          value.indexOf('ppp--pppoe') == -1
        );
        const arr = [];
        contents.forEach(item => {
          arr.push({
            mac: item.substring(colInfo[3], colInfo[4]).trim(),
            type: item.substring(colInfo[4], colInfo[5]).trim(),
            port: item.substring(colInfo[5], colInfo[6]).trim().split('/')[0].trim() + '/' + item.substring(colInfo[5], colInfo[6]).trim().split('/')[1].trim() + '/' + item.substring(colInfo[5], colInfo[6]).trim().split('/')[2].trim(),
            PhysicalPort: item.substring(colInfo[5], colInfo[6]).trim().split('/')[0].trim() + '/' + item.substring(colInfo[5], colInfo[6]).trim().split('/')[1].trim() + '/' + item.substring(colInfo[5], colInfo[6]).trim().split('/')[2].trim(),
            VPI: item.substring(colInfo[6], colInfo[7]).trim() == "-" ? "" : item.substring(colInfo[6], colInfo[7]).trim(),
            VCI: item.substring(colInfo[7], colInfo[8]).trim() == "-" ? "" : item.substring(colInfo[7], colInfo[8]).trim(),
            vlan: item.substring(colInfo[8], colInfo[9]).trim()
          });
        });
        resolve(arr);
      } catch (error) {
        reject(error);
      }
    });
  }
  // 获取speedprofile
  async getOltSpeedProfileIndex(me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        // username: this.options.RZUsername,
        username: 'rzadmin1',
        password: this.options.RZPassword,
        prompt: this.options.systemName,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_SPEEDPROFILEINDEX',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const msg = resultArr[0];
        const lines = msg
          .replace(/(-{2,})\sMore.*(\u001B\[37D)\s*\2/g, '')
          .split('\n');
        const titleArray = [
          'TID',
          'CIR',
          'CBS',
          'PIR',
          'PBS',
          'Pri',
          'Copy-policy',
          'Pri-policy',
        ];
        const colInfo = [];
        const title = lines.filter(
          value => value.indexOf(titleArray[0]) != -1
        );
        titleArray.forEach(titleItem =>
          colInfo.push(title[0].indexOf(titleItem))
        );
        const contents = lines.filter(
          value =>
          value.indexOf('---') == -1 &&
          value.indexOf('kbps') == -1 &&
          value.indexOf('Command') == -1 &&
          value.indexOf('Note') == -1 &&
          value.indexOf(this.options.systemName) == -1 &&
          value.indexOf('display') == -1 &&
          value.indexOf('Total') == -1 &&
          value.indexOf('config') == -1 &&
          value.indexOf(titleArray[0]) == -1 &&
          value.indexOf('>') == -1
        );
        const arr = [];
        contents.forEach(item => {
          arr.push({
            // name: item.substring(colInfo[0], colInfo[1]).trim(),
            index: item.substring(colInfo[0], colInfo[1]).trim(),
            // SIR: item.substring(colInfo[1], colInfo[2]).trim(),
            // CBS: item.substring(colInfo[2], colInfo[3]).trim(),
            // PIR: item.substring(colInfo[3], colInfo[4]).trim(),
            // PBS: item.substring(colInfo[4], colInfo[5]).trim(),
          });
        });
        resolve(arr);
      } catch (error) {
        reject(error);
      }
    });
  }
  async getOltSpeedProfile(index, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        // username: this.options.RZUsername,
        username: 'rzadmin1',
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        index,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_SPEEDPROFILE',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        console.log(resultArr);
        // resultArr.shift();
        const arr = [];
        for (let i = 0; i < resultArr.length; i++) {
          const name = resultArr[i]
            .substring(
              resultArr[i].indexOf('TD Name') + 7,
              resultArr[i].indexOf('Priority')
            )
            .replace(':', '')
            .trim();
          const SIR = resultArr[i]
            .substring(
              resultArr[i].indexOf('CIR') + 3,
              resultArr[i].indexOf('CBS')
            )
            .replace(':', '')
            .replace('kbps', '')
            .trim();
          const CBS = resultArr[i]
            .substring(
              resultArr[i].indexOf('CBS') + 3,
              resultArr[i].indexOf('PIR')
            )
            .replace(':', '')
            .replace('bytes', '')
            .trim();
          const PIR = resultArr[i]
            .substring(
              resultArr[i].indexOf('PIR') + 3,
              resultArr[i].indexOf('PBS')
            )
            .replace(':', '')
            .replace('kbps', '')
            .trim();
          const PBS = resultArr[i]
            .substring(
              resultArr[i].indexOf('PBS') + 3,
              resultArr[i].indexOf('Fix')
            )
            .replace(':', '')
            .replace('bytes', '')
            .trim();
          arr.push({
            name,
            SIR,
            CBS,
            PIR,
            PBS,
          });
        }
        resolve(arr);
      } catch (error) {
        reject(error);
      }
    });
  }
  // 设置oltacsvlan
  async setOltAcsVlan(acsVlan, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        acsVlan,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'SET_OLTACSVLAN',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resolve(true);
      } catch (error) {
        reject(error);
      }
    });
  }
  // 获取onuListMsg
  async getOnuListMsg(me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
      };
      try {
        const resultArray = [];
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'ONU_LIST',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const titleArray_1 = [2, 12, 33, 45, 54, 63, 72, 79];
        const titleArray_2 = [2, 12, 20];

        const arr = [];
        const msg = resultArr[0];
        if (msg.indexOf('There is no ONT available') != -1) {
          return resolve(arr);
        }
        // const result = msg.replace(/(-{2,})\sMore.*(\u001B\[37D)\s*\2/g, '').split('F/S/P');
        // result.shift();
        let result = msg.split(/-{2,}/g).filter(row => row.indexOf('display ont info') == -1 && row.indexOf('#') == -1 && row.indexOf('total') == -1)
        result=result.map(item=>item.replace('\n',''));
        for (let i = 0; i < result.length - 3; i += 5) {
          let valueRow1 = result[i + 1];
          const onus = valueRow1.split('\n').filter(item=>item.length>10);
          let valueRow2 = result[i + 3];
          const onuNames = valueRow2.split('\n').filter(item=>item.length>10);
          const colInfo1 = [2, 10, 13, 33, 45, 54, 63, 72,79];
          const colInfo2 = [2, 12, 19, 79];
          if(onus.length!==onuNames.length){
            return resolve(arr);
          }
          for(let i=0;i<onus.length;i++){
            let info = onus[i];
            let ONUname = onuNames[i].substring(colInfo2[2],colInfo2[3]).replace(/\n/g,'').trim();
            let fps = info.substring(colInfo1[0],colInfo1[1])
            const PONindex =
              fps.split('/')[0].trim() +
              '/' +
              fps.split('/')[1].trim() +
              '/' +
              fps.split('/')[2].trim();
            const ONUindex = info.substring(colInfo1[1],colInfo1[2]).trim();
            const onlyindex = PONindex + ':' + ONUindex;
            const sn = transSN(info.substring(colInfo1[2],colInfo1[3]).trim());
            const status = info.substring(colInfo1[4],colInfo1[5]).trim();
            const number = ONUindex;
            const slot = PONindex.split('/')[1].trim();
            const port = PONindex.split('/')[2].trim();
            let state = ""
            if (status == "offline") {
              state = "OffLine"
            } else if (status == "online") {
              state = "OnLine"
            }
            else {
              state = "N/A"
            }
            arr.push({
              PONindex,
              ONUindex,
              ONUname,
              onlyindex,
              sn,
              status: state,
              number,
              slot,
              port,
            });
          }
          
          // result[i] = result[i].replace(
          //   /(-{2,})\sMore.*(\u001B\[37D)\s*\2/,
          //   ''
          // );
          // const onuResult = result[i]
          //   .replace(/-{5,}/g, '|')
          //   .split('|')[1]
          //   .split('\n');
          // onuResult.pop();
          // onuResult.shift();
          // for (let j = 0; j < onuResult.length; j++) {
          //   const onu = onuResult[j]
          //     .trim()
          //     .replace(/\s{2,}/g, '|')
          //     .split('|');
          //   const PONindex =
          //     onu[0].split('/')[0].trim() +
          //     '/' +
          //     onu[0].split('/')[1].trim() +
          //     '/' +
          //     onu[0].split('/')[2].trim();
          //   const ONUindex = onu[1].trim();
          //   const onlyindex = PONindex + ':' + ONUindex;
          //   const sn = transSN(onu[2].trim());
          //   const status = onu[4].trim();
          //   const number = onu[1].trim();
          //   const slot = onu[0].split('/')[1].trim();
          //   const port = onu[0].split('/')[2].trim();
          //   let state = ""
          //   if (status == "offline") {
          //     state = "OffLine"
          //   } else if (status == "online") {
          //     state = "OnLine"
          //   }
          //   // else if(status == ""){
          //   //   state = ""
          //   // }else if(status == ""){
          //   //   state = ""
          //   // }
          //   else {
          //     state = "N/A"
          //   }
          //   arr.push({
          //     PONindex,
          //     ONUindex,
          //     onlyindex,
          //     sn,
          //     status: state,
          //     number,
          //     slot,
          //     port,
          //   });
          // }
          // const onuNameRow = result[i + 1].replace(/-{5,}/g, '|')
          //   .split('|')[1]
          //   .split('\n');
        }
        resolve(arr);
      } catch (error) {
        reject(error);
      }
    });
  }
  // 获取onuFindList
  async getUnregisteredONUList(me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'ONU_FIND',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const msg = resultArr[0];
        const resultArray = [];
        if (msg.indexOf('Failure') != -1) {
          return resolve(resultArray);
        }
        const arr = msg
          .replace(/.{5}More.*(\u001B\[37D)\s*\1/, '')
          .replace(/-{5,}/g, '|')
          .split('|');
        arr.shift();
        arr.pop();
        arr.forEach((item, index) => {
          const itemParams = item.replace(/\n/g, '|').split('|');
          let ONTSN = itemParams[3].split(':')[1];
          if (ONTSN.indexOf('(') != -1) {
            var ONTSNIndex = ONTSN.indexOf('(');
          } else {
            var ONTSNIndex = ONTSN.indexOf('Password');
          }
          ONTSN = ONTSN.substring(0, ONTSNIndex).trim();
          ONTSN = transSN(ONTSN);
          const PONindex = itemParams[2].split(':')[1].trim();
          const slot = PONindex.split('/')[1];
          const port = PONindex.split('/')[2];
          resultArray.push({
            PONindex,
            slot,
            port,
            sn: ONTSN,
            status: '',
          });
        });
        resolve(resultArray);
      } catch (error) {
        reject(error);
      }
    });
  }
  // 设置lineprofiletr069
  async setLineProfileTr069(lineprofile, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        lineprofile,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'SET_LINEPROFILETR069',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resolve(true);
      } catch (error) {
        reject(error);
      }
    });
  }
  // 设置已注册onu的acs地址
  async setRegisteredOnuAcsUrl(onuList, acsVlan, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        acsVlan,
        onuList,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'SET_REGISTEREDONUACSURL',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resolve(true);
      } catch (error) {
        reject(error);
      }
    });
  }
  // 添加card
  async createCard(slot, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        slot,
      };
      try {
        const fn = function (msg) {
          if (msg.indexOf('successfully') != -1) {
            return {
              result: true
            };
          }
          return {
            result: false,
            message: msg.split('\n')[1].trim()
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'CREATE_CARD',
            oltHardVersion: 'NONE',
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        if (resultArr.length != 0) {
          reject(resultArr);
        } else {
          resolve(true);
        }
      } catch (error) {
        reject(error);
      }
    });
  }
  // 删除card
  async deleteCard(slot, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        slot,
      };
      try {
        const fn = function (msg) {
          if (msg.indexOf('successfully') != -1) {
            return {
              result: true
            };
          }
          return {
            result: false,
            message: msg.split('\n')[1].trim()
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'CHANGE_ONUNAME',
            oltHardVersion: 'NONE',
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        if (resultArr.length != 0) {
          reject(resultArr);
        } else {
          resolve(true);
        }
      } catch (error) {
        reject(error);
      }
    });
  }
  // 开启所有ponport口
  async openAllPonPorts(ponarr, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        ponarr,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'OPEN_ALL_PONPORTS_STATUS',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resolve(true);
      } catch (error) {
        reject(error);
      }
    });
  }
  // 查询ponport的onus、光功率、距离
  async getPonPortMsg(portResult, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        portResult,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_PONPORTMSG',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const result = {
          onus: '',
          range: '',
          Txpwr: '',
          adminStatus: '',
          min: '',
          max: '',
        };
        result.onus = resultArr[0].split(',')[1].split(':')[1].trim();
        result.min = resultArr[1]
          .substring(
            resultArr[1].indexOf('Min distance(km)') + 16,
            resultArr[1].indexOf('Max distance(km)')
          )
          .trim();
        result.max = resultArr[1]
          .substring(
            resultArr[1].indexOf('Max distance(km)') + 16,
            resultArr[1].indexOf('Left')
          )
          .trim();
        result.range = result.min + '-' + result.max;
        result.adminStatus = resultArr[1].substring(resultArr[1].indexOf('Admin State') + 11, resultArr[1].indexOf('ONT encryption key switching interval(m)')).trim() == 'On' ? 'up' : 'down'
        if (resultArr[2].indexOf('Port Information') != -1) {
          // result.adminStatus = 'up';
          result.Txpwr = resultArr[2]
            .substring(
              resultArr[2].indexOf('TX power(dBm)') + 13,
              resultArr[2].indexOf('Optical Module Manufacturer Information')
            )
            .split('\n')[0]
            .trim();
        } else {
          // result.adminStatus = 'down';
          result.Txpwr = '';
        }
        resolve(result);
      } catch (error) {
        reject(error);
      }
    });
  }
  // 设置ponport距离和状态
  async setPonPortMsg(portResult, cmd, min, max, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        portResult,
        cmd,
        min,
        max,
      };
      try {
        const fn = function (msg) {
          if (msg.indexOf('%') != -1) {
            return {
              result: false,
              message: msg
                .substring(msg.indexOf('%') + 1, msg.indexOf(','))
                .trim(),
            };
          } else if (msg.indexOf('This board does not exist') != -1) {
            return {
              result: false,
              message: 'this board does not exist'
            };
          }
          return {
            result: true
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'SET_PONPORTMSG',
            oltHardVersion: 'NONE',
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        if (resultArr.length != 0) {
          reject(resultArr[0]);
        } else {
          resolve(true);
        }
      } catch (error) {
        reject(error);
      }
    });
  }
  // 获取uplink的tagvlan和untagvlan
  async getUplinkMsg(uplinkResult, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        uplinkResult,
      };
      try {
        const fn = function (msg) {
          if (
            msg.indexOf('Standby board does not support the operation') != -1
          ) {
            return {
              result: false,
              message: 'Standby board does not support the operation',
            };
          } else if (
            msg.indexOf('No configuration interface in standby board') != -1
          ) {
            return {
              result: false,
              message: 'Standby board does not support the operation',
            };
          }
          return {
            result: true
          };
        };
        let resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_UPLINKMSG',
            oltHardVersion: 'NONE',
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        console.log(resultArr);
        const result = {
          tagvlan: '',
          untagvlan: '',
          adminStatus: '',
        };
        if (resultArr[0].indexOf('not active') == -1) {
          result.adminStatus = 'up';
        } else {
          result.adminStatus = 'down';
        }
        result.tagvlan = resultArr[1] && resultArr[1]
          .replace(/-{5,}/g, '|')
          .split('|')[1]
          .trim()
          .replace(/\s{2,}/g, '|')
          .split('|')
          .join(',');
        result.untagvlan = resultArr[1] && resultArr[1]
          .substring(
            resultArr[1].indexOf('Native VLAN:') + 12,
            resultArr[1].indexOf(view.prompt)
          )
          .trim();
        resultArr = [];
        if (resultArr.length != 0) {
          reject(resultArr[0]);
        } else {
          if (result.tagvlan === undefined) {
            result.tagvlan = '';
          }
          if (result.untagvlan === undefined) {
            result.untagvlan = '';
          }
          resolve(result);
        }
      } catch (error) {
        reject(error);
      }
    });
  }
  // 修改uplink 状态、tagVlan、unTagVlan
  async setUplinkMsg(uplinkResult, tagVlan, removeTagVlan, cmd, unTagVlan, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        uplinkResult,
        tagVlan,
        removeTagVlan,
        cmd,
        unTagVlan,
      };
      try {
        const fn = function (msg) {
          if (msg.indexOf('The port is not in the VLAN') != -1) {
            return {
              result: false,
              message: 'The port is not in the VLAN'
            };
          }
          return {
            result: true
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'SET_UPLINKMSG',
            oltHardVersion: 'NONE',
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        if (resultArr.length != 0) {
          reject(resultArr[0]);
        } else {
          resolve(true);
        }
      } catch (error) {
        reject(error);
      }
    });
  }
  // 创建vlan
  async setVlan(vlanId, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        vlanId,
      };
      try {
        const fn = function (msg) {
          if (msg.indexOf('Failure') != -1) {
            return {
              result: false,
              message: msg
                .substring(
                  msg.indexOf('Failure:') + 8,
                  msg.indexOf(view.prompt)
                )
                .trim(),
            };
          }
          return {
            result: true
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'SET_VLAN',
            oltHardVersion: 'NONE',
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        if (resultArr.length != 0) {
          reject(resultArr[0]);
        } else {
          resolve(true);
        }
      } catch (error) {
        reject(error);
      }
    });
  }
  // 删除vlan
  async deleteVlan(vlanId, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        vlanId,
      };
      try {
        await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'DELETE_VLAN',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resolve(true);
      } catch (error) {
        reject(error);
      }
    });
  }
  // 创建speedprofile
  async speedProfileCreate(name, PIR, SIR, CBS, PBS, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        name,
        PIR,
        SIR,
        CBS,
        PBS,
      };
      try {
        const fn = function (msg) {
          if (msg.indexOf('Failure') != -1) {
            return {
              result: false,
              message: msg
                .substring(
                  msg.indexOf('Failure:') + 8,
                  msg.indexOf(view.prompt)
                )
                .trim(),
            };
          }
          return {
            result: true
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'CREATE_SPEEDPROFILE',
            oltHardVersion: 'NONE',
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        if (resultArr.length != 0) {
          reject(resultArr[0]);
        } else {
          resolve(true);
        }
      } catch (error) {
        reject(error);
      }
    });
  }
  // 修改speedprofile
  async speedProfileEdit(name, PIR, SIR, CBS, PBS, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        name,
        PIR,
        SIR,
        CBS,
        PBS,
      };
      try {
        const fn = function (msg) {
          if (msg.indexOf('Failure') != -1) {
            return {
              result: false,
              message: msg
                .substring(
                  msg.indexOf('Failure:') + 8,
                  msg.indexOf(view.prompt)
                )
                .trim(),
            };
          }
          return {
            result: true
          };

        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'EDIT_SPEEDPROFILE',
            oltHardVersion: 'NONE',
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        if (resultArr.length != 0) {
          reject(resultArr[0]);
        } else {
          resolve(true);
        }
      } catch (error) {
        reject(error);
      }
    });
  }
  // 删除speedprofile
  async speedProfileDelete(name, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        name,
      };
      try {
        const fn = function (msg) {
          if (msg.indexOf('Failure') != -1) {
            return {
              result: false,
              message: msg
                .substring(
                  msg.indexOf('Failure:') + 8,
                  msg.indexOf(view.prompt)
                )
                .trim(),
            };
          }
          return {
            result: true
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'DELETE_SPEEDPROFILE',
            oltHardVersion: 'NONE',
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        if (resultArr.length != 0) {
          reject(resultArr[0]);
        } else {
          resolve(true);
        }
      } catch (error) {
        reject(error);
      }
    });
  }
  // 创建onutype
  async onuProfileCreate(eth, pots, rf, name, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        eth,
        pots,
        rf,
        name,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'CREATE_ONUPROFILE',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resolve(true);
      } catch (error) {
        reject(error);
      }
    });
  }
  // 获取onutype
  async getOnuProfileMsg(onuProfileResult, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        onuProfileResult,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_ONUPROFILEMSG',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        const msg = resultArr[0];
        const result = {
          eth: 0,
          pots: 0,
          catv: 0,
        };
        if (msg.indexOf('Failure') != -1) {
          const err = msg
            .substring(msg.indexOf(':') + 1, msg.indexOf(view.prompt))
            .trim();
          reject(err);
        } else {
          const msg1 = msg.replace(/-{5,}/g, '|').split('|')[3];
          result.pots = msg1
            .substring(msg1.indexOf('POTS') + 4, msg1.indexOf('ETH'))
            .trim();
          result.eth = msg1
            .substring(msg1.indexOf('ETH') + 3, msg1.indexOf('VDSL'))
            .trim();
          result.catv = msg1.substring(msg1.indexOf('CATV') + 4).trim();
          resolve(result);
        }
      } catch (error) {
        reject(error);
      }
    });
  }
  // 修改onutype
  async onuProfileEdit(onuProfileResult, eth, pots, rf, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        onuProfileResult,
        eth,
        pots,
        rf,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'EDIT_ONUPROFILE',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resolve(true);
      } catch (error) {
        reject(error);
      }
    });
  }
  // 删除onutype
  async onuProfileDelete(onuProfileResult, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        onuProfileResult,
      };
      try {
        const fn = function (msg) {
          if (msg.indexOf('Failure') != -1) {
            return {
              result: false,
              message: msg
                .substring(
                  msg.indexOf('Failure:') + 8,
                  msg.indexOf(view.prompt)
                )
                .trim(),
            };
          }
          return {
            result: true
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'DELETE_ONUPROFILE',
            oltHardVersion: 'NONE',
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        if (resultArr.length != 0) {
          reject(resultArr[0]);
        } else {
          resolve(true);
        }
      } catch (error) {
        reject(error);
      }
    });
  }
  // 创建dbaProfile
  async dbaProfileCreate(name, type, max, fbw, abw, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        name,
        type,
        max,
        fbw,
        abw,
      };
      try {
        const resultArr = await common.run_EX(addr, {
          oltType: 'HUAWEI',
          mountPoint: 'CREATE_DBAPROFILE',
          oltHardVersion: 'NONE',
          view,
        }, null, me,
        view.username==='root');
        const msg = resultArr[0];
        if (msg.indexOf('Failure') != -1) {
          const err = msg.substring(msg.indexOf('Failure:') + 8, msg.indexOf(view.prompt)).trim();
          reject(err);
        } else {
          resolve(true);
        }
      } catch (error) {
        reject(error);
      }
    });
  }
  // 修改dbaprofile
  async dbaProfileEdit(name, type, max, fbw, abw, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        name,
        type,
        max,
        fbw,
        abw,
      };
      try {
        const fn = function (msg) {
          if (msg.indexOf('Failure') !== -1) {
            return {
              result: false,
              message: msg
                .substring(msg.indexOf(':') + 1, msg.indexOf(view.prompt))
                .trim(),
            };
          }
          return {
            result: true
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'EDIT_DBAPROFILE',
            oltHardVersion: 'NONE',
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        if (resultArr.length !== 0) {
          reject(resultArr[0]);
        } else {
          resolve(true);
        }
      } catch (error) {
        reject(error);
      }
    });
  }
  // 删除dbaProfile
  async dbaProfileDelete(name, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        name,
      };
      try {
        const fn = function (msg) {
          if (msg.indexOf('Failure') != -1) {
            return {
              result: false,
              message: msg
                .substring(msg.indexOf(':') + 1, msg.indexOf(view.prompt))
                .trim(),
            };
          }
          return {
            result: true
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'DELETE_DBAPROFILE',
            oltHardVersion: 'NONE',
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        if (resultArr.length != 0) {
          reject(resultArr[0]);
        } else {
          resolve(true);
        }
      } catch (error) {
        reject(error);
      }
    });
  }
  // 创建lineprofile
  async lineProfileCreate(name, bussinessArr, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        name,
        arr: bussinessArr,
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'CREATE_LINEPROFILE',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resolve(true);
      } catch (error) {
        reject(error);
      }
    });
  }
  
  // 删除lineprofile
  async lineProfileDelete(name, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        name,
      };
      try {
        const fn = function (msg) {
          if (msg.indexOf('Failure') != -1) {
            return {
              result: false,
              message: msg
                .substring(
                  msg.indexOf('Failure:') + 8,
                  msg.indexOf(view.prompt)
                )
                .trim(),
            };
          }
          return {
            result: true
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'DELETE_LINEPROFILE',
            oltHardVersion: 'NONE',
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        if (resultArr.length != 0) {
          reject(resultArr[0]);
        } else {
          resolve(true);
        }
      } catch (error) {
        reject(error);
      }
    });
  }

  async changeOnuName(data,me){
     
      return new Promise(async(resolve,reject)=>{
       
        const addr = this.options.ip +':'+this.options.tPort;
        const view = {
          username: this.options.RZUsername,
          password: this.options.RZPassword,
          prompt: this.options.systemName,
          ManagementPassword: this.options.managementPassword,
          data,
        }
        let fn = val=>{
          console.log(val)
        }
        try{
          await common.run_EX(
            addr, {
              oltType: 'HUAWEI',
              mountPoint: 'CHANGE_ONUNAME',
              oltHardVersion: 'NONE',
              view,
            },
            fn,
            me,
            view.username==='root'
          );


          resolve('success')
        } catch(error){
          reject(error);
        }
      })
  }
  async lineProfileNameCheck(name, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        name,
      };
      try {
        const fn = function (msg) {
          if (msg.indexOf('Failure') != -1) {
            return {
              result: false,
              message: msg
                .substring(
                  msg.indexOf('Failure:') + 8,
                  msg.indexOf(view.prompt)
                )
                .trim(),
            };
          }
          return {
            result: true
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'GET_LINEPROFILELIST',
            oltHardVersion: 'NONE',
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        // if (resultArr.length != 0) {
        //   reject(resultArr[0]);
        // } else {
        //   resolve(true);
        // }
        const msg = resultArr && resultArr[0];
        const lines = msg
          .replace(/(-{2,})\sMore.*(\u001B\[37D)\s*\2/g, '')
          .split('\n');
        const titleArray = ['Profile-ID', 'Profile-name', 'Binding times'];
        const colInfo = [];
        const title = lines.filter(
          value => value.indexOf(titleArray[0]) != -1
        );
        titleArray.forEach(titleItem =>
          colInfo.push(title[0].indexOf(titleItem))
        );
        const contents = lines.filter(
          value =>
          value.indexOf('---') == -1 &&
          value.indexOf('Total') == -1 &&
          value.indexOf('config') == -1 &&
          value.indexOf('display') == -1 &&
          value.indexOf(titleArray[0]) == -1 &&
          value.indexOf('>') == -1
        );
        const arr = [];
        contents.forEach(item => {
          arr.push({
            profileID: item.substring(colInfo[0], colInfo[1]).trim(),
            profileName: item.substring(colInfo[1], colInfo[2]).trim(),
            bindingTimes: item.substring(colInfo[2], colInfo[3]).trim(),
          });
        });
        resolve(arr);
      } catch (error) {
        reject(error);
      }
    });
  }
  async reboot(ponIndex, onuIndex, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const F = ponIndex.split('/')[0];
      const S = ponIndex.split('/')[1];
      const P = ponIndex.split('/')[2];
      const cmd = `ont reset ${P} ${onuIndex}`;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        F,
        S,
        cmd
      };
      try {
        const fn = function (msg) {
          if (msg.indexOf('Failure') != -1) {
            return {
              result: false,
              message: msg
                .substring(
                  msg.indexOf('Failure:') + 8,
                  msg.indexOf(view.prompt)
                )
                .trim(),
            };
          }
          return {
            result: true
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'REBOOT_ACTIVE',
            oltHardVersion: 'NONE',
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        console.log(resultArr);
        resolve(true);
      } catch (error) {
        reject(error)
      }
    })
  }
  async disable(ponIndex, onuIndex, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const F = ponIndex.split('/')[0];
      const S = ponIndex.split('/')[1];
      const P = ponIndex.split('/')[2];
      const cmd = `ont deactivate ${P} ${onuIndex}`;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        F,
        S,
        cmd
      };
      try {
        const fn = function (msg) {
          if (msg.indexOf('Failure') != -1) {
            return {
              result: false,
              message: msg
                .substring(
                  msg.indexOf('Failure:') + 8,
                  msg.indexOf(view.prompt)
                )
                .trim(),
            };
          }
          return {
            result: true
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'REBOOT_ACTIVE',
            oltHardVersion: 'NONE',
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        resolve(true)
      } catch (error) {
        reject(error)
      }
    })
  }
  async restoreONU(ponIndex, onuIndex, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const F = ponIndex.split('/')[0];
      const S = ponIndex.split('/')[1];
      const P = ponIndex.split('/')[2];
      const cmd = `ont factory-setting-restore ${P} ${onuIndex}`;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        F,
        S,
        cmd
      };
      try {
        const fn = function (msg) {
          if (msg.indexOf('Failure') != -1) {
            return {
              result: false,
              message: msg
                .substring(
                  msg.indexOf('Failure:') + 8,
                  msg.indexOf(view.prompt)
                )
                .trim(),
            };
          }
          return {
            result: true
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'REBOOT_ACTIVE',
            oltHardVersion: 'NONE',
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        resolve(true)
      } catch (error) {
        reject(error)
      }
    })
  }
  async enable(ponIndex, onuIndex, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      const F = ponIndex.split('/')[0];
      const S = ponIndex.split('/')[1];
      const P = ponIndex.split('/')[2];
      const cmd = `ont activate ${P} ${onuIndex}`;
      const addr = this.options.ip + ':' + this.options.tPort;
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        ManagementPassword: this.options.managementPassword,
        F,
        S,
        cmd
      };
      try {
        const fn = function (msg) {
          if (msg.indexOf('Failure') != -1) {
            return {
              result: false,
              message: msg
                .substring(
                  msg.indexOf('Failure:') + 8,
                  msg.indexOf(view.prompt)
                )
                .trim(),
            };
          }
          return {
            result: true
          };
        };
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'REBOOT_ACTIVE',
            oltHardVersion: 'NONE',
            view,
          },
          fn,
          me,
          view.username==='root'
        );
        resolve(true)
      } catch (error) {
        reject(error)
      }
    })
  }
  async setCatvState(onuResult, catvstate, me) {
    return new Promise(async (resolve, reject) => {
      me.proxyFlag = this.options.proxyFlag;
      let cmd
      if (catvstate == "true") {
        cmd = "on"
      } else if (catvstate == "false") {
        cmd = "off"
      }
      const addr = this.options.ip + ':' + this.options.tPort;
      // 组装模板变量
      const view = {
        username: this.options.RZUsername,
        password: this.options.RZPassword,
        prompt: this.options.systemName,
        onuResult,
        cmd
      };
      try {
        const resultArr = await common.run_EX(
          addr, {
            oltType: 'HUAWEI',
            mountPoint: 'SET_CATVSTATE',
            oltHardVersion: 'NONE',
            view,
          },
          null,
          me,
          view.username==='root'
        );
        resolve(true);
      } catch (error) {
        reject(error);
      }
    });
  }
}

function transSN(sn) {
  if (sn.length <= 8) {
    return sn;
  }
  const arr = [];
  for (let i = 0; i < 8; i = i + 2) {
    arr.push(parseInt(sn.substr(i, 2), 16));
  }
  const buffer = Buffer.from(arr);
  return buffer.toString() + sn.substring(8);
}

module.exports = HWOLT;